import cron from './cron';

function getDate(options) {
	const nowDate = new Date();

	const defaults = Object.assign({
			start: 1900,
			end: 2100,
			defaultValue: [nowDate.getFullYear(), nowDate.getMonth() + 1, nowDate.getDate()],
			cron: '* * *'
	}, options);

	// 兼容原来的 start、end 传 Number 的用法
	if (typeof defaults.start === 'number') {
			defaults.start = new Date(`${defaults.start}/01/01`);
	}
	else if (typeof defaults.start === 'string') {
		let date = new Date(defaults.start.replace(/-/g, '/'))
		defaults.start = new Date(date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate());
	}
	if (typeof defaults.end === 'number') {
			defaults.end = new Date(`${defaults.end}/12/31`);
	}
	else if (typeof defaults.end === 'string') {
		let date = new Date(defaults.end.replace(/-/g, '/'))
		defaults.end = new Date(date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate());
	}

	const findBy = (array, key, value) => {
			for(let i = 0, len = array.length; i < len; i++){
					const obj = array[i];
					if(obj[key] == value){
							return obj;
					}
			}
	};

	const date = [];
	const interval = cron.parse(defaults.cron, defaults.start, defaults.end);
	let obj;
	do {
			obj = interval.next();

			const year = obj.value.getFullYear();
			const month = obj.value.getMonth() + 1;
			const day = obj.value.getDate();

			let Y = findBy(date, 'value', year);
			if (!Y) {
					Y = {
							label: year + '年',
							value: year,
							children: []
					};
					date.push(Y);
			}
			let M = findBy(Y.children, 'value', month);
			if (!M) {
					M = {
							label: month + '月',
							value: month,
							children: []
					};
					Y.children.push(M);
			}
			M.children.push({
					label: day + '日',
					value: day
			});
	}
	while (!obj.done);

	return date;
}

export default {
	getDate
};